function supportstorage() {
    if (typeof window.localStorage == 'object')
        return true;
    else
        return false;
}

function handleSaveLayout() {
    var e = $(".demo").html();
    if (!stopsave && e != window.demoHtml) {
        stopsave++;
        window.demoHtml = e;
        saveLayout();
        stopsave--;
    }
}

var layouthistory;
function saveLayout() {
    var data = layouthistory;
    if (!data) {
        data = {};
        data.count = 0;
        data.list = [];
    }
    if (data.list.length > data.count) {
        for (i = data.count; i < data.list.length; i++)
            data.list[i] = null;
    }
    data.list[data.count] = window.demoHtml;
    data.count++;
    if (supportstorage()) {
        localStorage.setItem("layoutdata", JSON.stringify(data));
    }
    layouthistory = data;
}

function undoLayout() {
    var data = layouthistory;
    if (data) {
        if (data.count < 2) return false;
        window.demoHtml = data.list[data.count - 2];
        data.count--;
        $('.demo').html(window.demoHtml);
        if (supportstorage()) {
            localStorage.setItem("layoutdata", JSON.stringify(data));
        }
        return true;
    }
    return false;
}

function redoLayout() {
    var data = layouthistory;
    if (data) {
        if (data.list[data.count]) {
            window.demoHtml = data.list[data.count];
            data.count++;
            $('.demo').html(window.demoHtml);
            if (supportstorage()) {
                localStorage.setItem("layoutdata", JSON.stringify(data));
            }
            return true;
        }
    }
    return false;
}

function configurationElm(e, t) {
    $(".demo").delegate(".configuration > a", "click", function (e) {
        e.preventDefault();
        var t = $(this).parent().next().next().children();
        $(this).toggleClass("active");
        t.toggleClass($(this).attr("rel"))
    });
    $(".demo").delegate(".configuration .dropdown-menu a", "click", function (e) {
        e.preventDefault();
        var t = $(this).parent().parent();
        var n = t.parent().parent().next().next().children();
        t.find("li").removeClass("active");
        $(this).parent().addClass("active");
        var r = "";
        t.find("a").each(function () {
            r += $(this).attr("rel") + " "
        });
        t.parent().removeClass("open");
        n.removeClass(r);
        n.addClass($(this).attr("rel"))
    })
}

function removeElm() {
    $(".demo").delegate(".remove", "click", function (e) {
        e.preventDefault();
        var $index = $(this).parent().attr('index');
        $('.sidebar-nav .lyrow').eq($index).show();
        $(this).parent().remove();
        if (!$(".demo .lyrow").length > 0) {
            clearDemo()
        }
    })
}

function clearDemo() {
    $(".demo").empty();
    layouthistory = null;
    if (supportstorage())
        localStorage.removeItem("layoutdata");
}

function timeCheck() {
    $('.viewHead .submit').click(function () {
        var $begin = $(this).parent().find('input[name="begin"]').val();
        var $end = $(this).parent().find('input[name="end"]').val();
        $(this).find('input:eq(0)').val($begin);
        $(this).find('input:eq(1)').val($end);
    })
}

function compare() {
    var $h = $(window).height() / 2,
        $chx = $h - (($h / 100) * 2) - 34;
    var $html = '<div class="lyrow small ui-draggable">' +
        '<a href="#close" class="remove label label-important"><i class="icon-remove icon-white"></i></a>' +
        '<span class="drag label">比较</span><div class="row-fluid clearfix"><div class="span12 column" style="min-height: ' + $h + 'px;">' +
        '<div class="compare" style="min-height:' + $chx + 'px;"></div></div></div></div>';
    $('.toolbars .compare').click(function () {
        $($html).appendTo('.main');
    })
}

var timerSave = 1000;
var stopsave = 0;
var startdrag = 0;
var demoHtml = $(".demo").html();
var num = 0;

function restoreData() {
    if (supportstorage()) {
        layouthistory = JSON.parse(localStorage.getItem("layoutdata"));
        if (!layouthistory) return false;
        window.demoHtml = layouthistory.list[layouthistory.count - 1];
        if (window.demoHtml) $(".demo").html(window.demoHtml);
    }
}

function initContainer() {

    $(".demo,.demo .compare").sortable({
        connectWith: ".compare",
        opacity: .35,
        helper: function () {
            return '<div style="width:' + $(this).offsetWidth + 'px;height:' + $(this).offsetheight + 'px;z-index:' + 1001 + ';background:#FFF;"></div>';
        },
        handle: ".drag",
        start: function (e, t) {
            if (!startdrag) stopsave++;
            startdrag = 1;
        },
        stop: function (e, t) {
            if (stopsave > 0) stopsave--;
            startdrag = 0;
        }
    });

    //configurationElm();//导航栏
}

$iframe = [
    'http://192.168.77.119:8088/Iridium/public/',
    'http://192.168.77.119:8088/Iridium/public/',
    'http://192.168.77.119:8088/Iridium/public/public/toAllinfo?mainflg=allinfo',
    'http://baidu.com'
];

function copyContainer() {
    $(".sidebar-nav .lyrow").draggable({
        connectToSortable: ".demo",
        helper: "clone",
        handle: ".drag",
        start: function (e, t) {
            if (!startdrag) stopsave++;
            startdrag = 1;
        },
        drag: function (e, t) {
            t.helper.width(400);
            t.helper.height(400);
        },
        stop: function (e, t) {
            $(".demo .compare").sortable({
                opacity: .35,
                connectWith: ".compare",
                start: function (e, t) {
                    if (!startdrag) stopsave++;
                    startdrag = 1;
                },
                stop: function (e, t) {
                    if (stopsave > 0) stopsave--;
                    startdrag = 0;
                }
            });
            if (stopsave > 0) stopsave--;
            startdrag = 0;
            var $pid = $(this).attr('index'),
                $this = $(this),
                numberx;
            $('.main [index]').each(function () {
                var ids = $(this).attr('index');
                if ($('.main [index=' + ids + ']').length >= 1) {
                    numberx = $(this).attr('index');
                    if (numberx != null && numberx == $pid) {
                        $this.hide();
                        $(this).find('.model-data').attr('src', $iframe[$pid]);
                    }
                }
            })
            var $winh = $(window).height(),
                $wins = $winh / 2,
                $hx = $wins - (($wins / 100) * 3) - 34,
                $hxx = $winh - (($winh / 100) * 3) - 40;
            if ($('.main .lyrow').length > 1) {
                $('.main .lyrow').removeClass('large').addClass('small');
                $('.demo .small .column').css('min-height', $wins);
                $('.demo .small .model-data').css('min-height', $hx);
            } else {
                $('.demo .large .column').css('min-height', $winh);
                $('.demo .large .model-data').css('min-height', $hxx);
            }
        }
    });
    viewListening();
    //scrollbar();//视图区域滚动条
}

function viewListening() {
    mainHtml();
    var $lyrow = $('.main [index]'),
        $li = $('.sidebar-nav .lyrow'),
        $ids = [];
    $.each($lyrow, function () {
        $ids += $(this).attr('index');
    })
    for (var j = 0; j < $ids.length; j++) {
        $li.eq($ids[j]).hide();
    }
}

function mainHtml() {
    var $h = $(window).height();
    var $main = $('.main').html(),
        $li = $('.sidebar-nav .lyrow'),
        $liText = $li.eq(3).find('.drag').text(),
        $mainHTML = '<div class="lyrow large ui-draggable" index="3">' +
            '<a href="#close" class="remove label label-important"><i class="fa fa-remove"></i></a>' +
            '<span class="drag label tl">' + $liText + '</span><div class="row-fluid clearfix"><div class="span12 column" style="min-height: ' + $h + 'px;">' +
            '<div class="viewHead"><div class="crowd">吞吐量(流入和流出)</div><div class="begin"><input type="text" name="begin" class="dtpicker"></div><div class="line">—</div>' +
            '<div class="end"> <input type="text" name="end" class="dtpicker"> </div><div class="lastHour">最近一小时</div><div class="submit"><i class="fa fa-check-square-o"></i></div></div>' +
            '<iframe class="model-data" src="' + $iframe[3] + '"></iframe></div></div></div>';
    if ($main == '' || $main == undefined || $main == null) {
        $($mainHTML).prependTo('.main');
    }
}

function viewZoom() {
    $('.demo').on('dblclick', '.drag', function (e) {
        e.preventDefault();
        var $thisPar = $(this).parent();
        $(this).parent().toggleClass('large');
        $(this).parent().toggleClass('small');
        var $whx = $(window).height(),
            $wh = $whx / 2,
            $hx = $wh - (($wh / 100) * 3) - 34,
            $hxx = $whx - (($whx / 100) * 3) - 40;
        $('.demo .small .column').css('min-height', $wh);
        $('.demo .large .column').css('min-height', $whx);

        $('.demo .large .model-data').css('min-height', $hxx);
        $('.demo .small .model-data').css('min-height', $hx);

        if ($thisPar.has('large')) {
            num = 1;
        } else if ($thisPar.has('small')) {
            num = 0;
        }
    });
}

function viewZoom2() {
    $('.t-size').on('click', function () {
        var $whx = $(window).height(),
            $wh = $whx / 2,
            $hx = $wh - (($wh / 100) * 3) - 34,
            $hxx = $whx - (($whx / 100) * 3) - 40;
        if (num == 0) {
            num = 1;
            $('.main .lyrow').removeClass('large').addClass('small');
            $('.demo .small .column').css('min-height', $wh);
            $('.demo .small .model-data').css('min-height', $hx);
        } else if (num == 1) {
            num = 0;
            $('.main .lyrow').removeClass('small').addClass('large');
            $('.demo .large .column').css('min-height', $whx);
            $('.demo .large .model-data').css('min-height', $hxx);
        }
    })
}

function clearView() {
    $("#clear").click(function (e) {
        e.preventDefault();
        clearDemo()
        $('.sidebar-nav .lyrow').show();
    });
}

function contrast() {
    $('.contrast').on('click', function () {
        $('.main .model-data').each(function () {
            $(this).attr('src', 'http://192.168.77.119:8088/Iridium/public/setting/toSetting');
        })
    })
}
// 居中
function center(obj) {
    var screenWidth = $(window).width(), screenHeight = $(window).height(); //当前浏览器窗口的 宽高
    var scrolltop = $(document).scrollTop();//获取当前窗口距离页面顶部高度
    var objLeft = (screenWidth - obj.width()) / 2;
    var objTop = (screenHeight - obj.height()) / 2 + scrolltop;
    obj.css({left: objLeft + 'px', top: objTop + 'px'});
    //浏览器窗口大小改变时
    $(window).resize(function () {
        screenWidth = $(window).width();
        screenHeight = $(window).height();
        scrolltop = $(document).scrollTop();
        objLeft = (screenWidth - obj.width()) / 2;
        objTop = (screenHeight - obj.height()) / 2 + scrolltop;
        obj.css({left: objLeft + 'px', top: objTop + 'px'});
    });
    //浏览器有滚动条时的操作、
    $(window).scroll(function () {
        screenWidth = $(window).width();
        screenHeight = $(window).height();
        scrolltop = $(document).scrollTop();
        objLeft = (screenWidth - obj.width()) / 2;
        objTop = (screenHeight - obj.height()) / 2 + scrolltop;
        obj.css({left: objLeft + 'px', top: objTop + 'px'});
    });
}

function checkIp() {
    $('.ip_add input').each(function () {
        var $id = $(this);
        ipPort($id);
    })
}

function addMove() {
    $('.server .increase .fa-plus-square-o').on('click', function () {
        var $val = $(this).prev().val(),
            $parent = $(this).parents('.server').prev(),
            $prevHTML = $parent.html(),
            $addHTML = '<div class="server">' + $prevHTML + '<div class="label clear"><i class="fa fa-times"></i></div></div>';
            console.log($prevHTML);
        if ($val == '' || $val == null) $val = 1;
        for (var i = 1; i <= $val; i++) {
            $parent.after($addHTML);
        }
        checkIp();//检测IP端口
        var $caption = $('.a_content .server caption');
        for (var j = 0; j < $caption.length; j++) {
            $($caption[j]).text('设备' + (j + 1));
        }

        $('.server .clear').click(function () {
            $(this).parent().remove();
        })
    })
}

$(window).resize(function () {
    var $whxxx = $(window).height(),
        $wh = $whxxx / 2,
        $whx = $wh - (($wh / 100) * 3) - 34,
        $whxx = $whxxx - (($whxxx / 100) * 3) - 40;
    $('.demo .large .column').css('min-height', $whxx);
    $('.demo .small .column').css('min-height', $wh);
    $('.demo .large .model-data').css('min-height', $whxx);
    $('.demo .small .model-data').css('min-height', $whx);

})

$(document).ready(function () {
    restoreData();
    var $whx = $(window).height(),
        $wh = $whx / 2,
        $hx = $wh - (($wh / 100) * 3) - 34,
        $hxx = $whx - (($whx / 100) * 3) - 40;
    window.onload = function () {
        $('.demo .large .column').css('min-height', $whx);
        $('.demo .large .model-data').css('min-height', $hxx);
    }
    /*时间插件*/
    $('.dtpicker').datetimepicker({
        lang: 'ch',
        timepicker: true,
        step: 5,

        format: 'Y-m-d H:i',
        formatDate: 'Y-m-d',
        formatTime: 'H:i',
        minDate: '-1971-01-02', // yesterday is minimum date
        maxDate: '+1970-01-01' // and tommorow is maximum date calendar
    });

    copyContainer();//左侧服务器拖动到视图区域
    initContainer();//视图区域的视图拖动
    clearView();//一键清空视图区域

    $(".a_content").mCustomScrollbar({theme: "minimal-dark"});

    $('#undo').click(function () {
        stopsave++;
        if (undoLayout()) initContainer();
        stopsave--;
    });

    var _addHTMl = $('.a_content .mCSB_container').html();
    $('.addServer').on('click', function () {
        var $addServer = $('.add_server');
        $('.bg_back').show();
        $addServer.show();
        checkIp();//检测IP端口
        addMove();//添加更多设备
        ipPort('.increase input');//检测添加的输入框

        function addHide() {
            $('.bg_back').hide();
            $addServer.hide();
            $('.a_content .mCSB_container').html(_addHTMl);
        }

        $('.add_server .remove').click(function () {
            addHide();
        })

        $('.bg_back').click(function () {
            $addServer.addClass('pulse').bind('animationend webkitAnimationEnd MSAnimationEnd oAnimationEnd', function () {
                $addServer.removeClass('pulse');
            });
        })
    })


    center($('.add_server'));//弹出层居中


    $('#redo').click(function () {
        stopsave++;
        if (redoLayout()) initContainer();
        stopsave--;
    });
    contrast();//切换管理设置
    timeCheck();//获取时间
    compare();//比较
    viewZoom();//视图双击缩放
    viewZoom2();//单击全视图缩放
    removeElm();//单个视图关闭
    setInterval(function () {
        handleSaveLayout();
    }, timerSave);


})